
module ESI
  class Config

    attr_reader :config
    
    def initialize(config_file)
      @config = YAML.load_file( config_file || "config/esi.yml" )
      @path_root = File.dirname( config_file || "config/esi.yml" )
      #@config.symbolize_keys!
    end

    # access configuration values
    def [](key)
      @config[key]
    end

    def enable_esi_processor?( headers )
      # check for surrogate control configuration
      # check for matching content type
      # if both are set it surrogate takes presendence 
      use_esi = false
      surrogate_enabled = @config['enable_surrogate_control']
      match_content_type = @config['match_content_type_text']

      if match_content_type
        use_esi = /^text\//.match(headers["Content-Type"])
      end

      if surrogate_enabled
        use_esi = /ESI/.match(headers["Surrogate-Control"])
      end

      use_esi
    end
 
    # returns the cache object as given in the config/esi.yml
    # cache: key, or defaults to ruby as in uses this process
    # the options allowed are ruby and memcache
    def cache
			cache_type = @config['cache']
			options = @config[cache_type.to_s] || {}
      # always return the same cache object, per process
      $cache ||= case cache_type
      when 'ruby'
        ESI::RubyCache.new(options)
      when 'memcached'
        ESI::MemcachedCache.new(options)
      else
        raise "Unsupported cache"
      end
    end

    # return true/false depending on the value of 
    # invalidator: on/off
    # within in config/esi.yml
    def start_invalidator?
      @config['invalidator']
    end

  end    
end

